﻿using System;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;

namespace iStudio.Engine
{
    /// <summary>
    /// NAudio meter provider wrapper for iStudio
    /// </summary>
    internal class NAudioMeter : INAudioStream
    {
        private readonly MeteringSampleProvider _meter;
        private readonly INAudioStream _source;

        public event EventHandler<StreamVolumeEventArgs> StreamVolume;

        public NAudioMeter (INAudioStream source, int size)
        {
            _meter = new MeteringSampleProvider(source, size);
            _meter.StreamVolume += MeterOnStreamVolume;

            _source = source;
        }

        private void MeterOnStreamVolume(object sender, StreamVolumeEventArgs streamVolumeEventArgs)
        {
            StreamVolume(this, streamVolumeEventArgs);
        }

        public long Position
        {
            get
            {
                return _source.Position;
            }
            set
            {
                if (_source.Position != value)
                {
                    _source.Position = value;
                }
            }
        }

        public long Length
        {
            get
            {
                return _source.Length;
            }
        }

        public WaveFormat WaveFormat
        {
            get
            {
                return _source.WaveFormat;
            }
        }

        public int Read(float[] buffer, int offset, int count)
        {
            return _meter.Read(buffer, offset, count);
        }
    }
}
